package org.example.nettydemo.netty.redis;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.redis.*;

/**
 * @author liujing
 */

public class NettyRedisClient {
    private final String host;
    private final int port;
    private final String password;

    public NettyRedisClient(String host, int port, String password) {
        this.host = host;
        this.port = port;
        this.password = password;
    }

    public void connect() {
        // 创建Netty的事件循环组（用于管理线程），干活的工人
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // 配置Netty客户端
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class) // 使用NIO进行网络通信
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加Redis协议编解码器
                            pipeline.addLast(new RedisDecoder());
                            pipeline.addLast(new RedisBulkStringAggregator()); // 处理批量字符串
                            pipeline.addLast(new RedisArrayAggregator()); // 处理数组数据
                            pipeline.addLast(new RedisEncoder());
                            // 自定义业务逻辑处理器
                            pipeline.addLast(new RedisClientHandler(password));
                        }
                    });

            // 连接Redis服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();
            // 监听连接关闭事件
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭Netty线程组
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        // 连接到Redis服务器（请替换成你的Redis地址、端口和密码）
        NettyRedisClient client = new NettyRedisClient("127.0.0.1", 6379, "888");
        client.connect();
    }
}





